import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';

import { ValidatorsService } from '../shared/services/public/validators/validators.service';
import { ApisService } from '../shared/services/requests/apis.service';
import { RequestsService } from '../shared/services/requests/requests.service';
import { login } from '../shared/interface/datas/login';
import { IfLoginService } from '../shared/services/public/if-login/if-login.service';

// component 装饰器
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
// LoginComponent 类
export class LoginComponent implements OnInit {

  // 登录的FormGroup
  private loginForm:FormGroup;

  private loading = false;

  private loginApi = this.apis.apis.login;

  constructor(private fb:FormBuilder,
              private router:Router,
              private validatorsService:ValidatorsService,
              private apis:ApisService,
              private req:RequestsService,
              private ifLogin:IfLoginService) {
    // 创建表单
    this.createForm();
  }

  // 需要注入的校验规则
  private validators = this.validatorsService.validators;  // 校验规则集
  private v_userName = this.validators.userName;  // 登录的校验规则
  private v_passWord = this.validators.passWord;  // 密码的校验规则

  /** 创建表单 */
  private createForm() {
    this.loginForm = this.fb.group({
      // 用户名
      userName: ['',
        this.v_userName.valids()
      //  [
      //  // 校验规则
      //  Validators.required,
      //  this.v_userName.min(),
      //  this.v_userName.max,
      //  this.v_userName.pattern
      //]
      ],
      // 密码
      passWord: ['',
        this.v_passWord.valids()
        //[
        //  // 校验规则
        //  this.v_passWord.required,
        //  this.v_passWord.min,
        //  this.v_passWord.max
        //]
      ]
    })
  }

  /** 登录 */
  private loginFun():void {
    if (this.loginForm.valid) {
      this.loading = true;

      // 提交字段
      let data = {
        name: this.loginForm.value.userName,
        pass: this.loginForm.value.passWord
      };

      this.req.editData(this.loginApi, data)
        .subscribe(
          res => {
            res as login;
            /** 成功 */
            this.ifLogin.changeIfLogin(true);
            this.router.navigate(['dashboard']);
            this.loading = false;

          },
          err => {
            /** 错误 */
            this.ifLogin.changeIfLogin(false);
            this.loading = false;
          }
        )
    } else {
      return;
    }
  }

  ngOnInit() {

  }

}
